//
//  VVStatusViewModel.swift
//  Weibo
//
//  Created by 王惠平 on 2017/3/31.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit

//处理cell数据显示逻辑
class VVStatusViewModel: NSObject {

    //引用微博模型数据
    var status: VVStatus? {
        
        didSet {
            
            //获取认证类型的数据
            let verifiedType = status?.user?.verified_type ?? 0
            
            //处理认证类型图片的图片
            hanleVerifiedTyeImage(verifiedType:verifiedType)
            
            //获取会员等级
            let mbrank = status?.user?.mbrank ?? 0
            
            //处理会员等级图片1-6
            handleMbrankImage(mbrank: mbrank)
            
            if let currentStatus = status {
                
                handleReweetConten(status: currentStatus)
            }
            
            //处理来源数据
            handleSourceContent(source: status?.source ?? "")
            
            //处理原创微博富文本
            originalAtttibutedString = handleEmoticonAttributedString(status: status?.text ?? "" )
            
        }
    }
    
    //原创微博的富文本
    var originalAtttibutedString: NSAttributedString?
    
    //转发微博的富文本
    var retweetAttributedString: NSAttributedString?
    
    //认证类型等级图片
    var verifiedTypeImage: UIImage?
    
    //会员等级图片
    var mbrankImage: UIImage?
    
    //转发微博内容
    var retweetContent: String?
    
    //来源
    var sourceContent: String?
    
    //只读计算属性,每次获取时间的时候都要跟当前时间进行对比
    var timeContent: String? {
        
        //判断时间是否为空
        guard let createAt = status?.created_at else {
            
            return nil
        }
        
        let dt = DateFormatter()
        
        if isTheYear(createAt: createAt) {
            
            //今年(获取当前的日历对象)
            let calender = Calendar.current
            
            //是否是今天
            if calender.isDateInToday(createAt) {
                
                //是今天
                //获取发微博时间和当前的时间的差
                let timeIntever = abs(createAt.timeIntervalSinceNow)
                
                if timeIntever < 60 {
                    
                    //1分钟之前
                    return "刚刚"
                    
                } else if timeIntever < 3600 {
                    
                    //1小数之前
                    let result = Int(timeIntever / 60)
                    
                    return "\(result)分钟前"
                } else {
                    
                    //其他
                    let result = Int(timeIntever / 3600)
                    
                    return "\(result)小时前"
                }
            } else if calender.isDateInYesterday(createAt) {
                
                dt.dateFormat = "昨天 HH:mm"
            } else {
                
                dt.dateFormat = "MM-dd HH:mm"
            }
            
        } else {
            
            //不是今年
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        
        return dt.string(from: createAt)
    }
    
    //根据传入的时间判断是否是今年
    fileprivate func isTheYear(createAt: Date) ->Bool {
        
        let dt = DateFormatter()
        
        //只获取年份
        dt.dateFormat = "yyyy"
        
        //获取发微博时间的年份
        let crearAtYear = dt.string(from: createAt)
        
        
        //获取当前时间的年份
        let currentDateYear = dt.string(from: Date())
        
        
        //判断是否是同一年
        return crearAtYear == currentDateYear
        
        
    }
    
    //处理微博富文本的方法
    fileprivate func handleEmoticonAttributedString(status: String) ->NSAttributedString {
        
        //把微博内容字符串转成富文本
        let attributedStr = NSMutableAttributedString(string: status)
        
        //匹配表情描述
        let regular = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: [])
        
        //匹配微博内容的表情描述
        let matchReulstArray = regular.matches(in: status, options: [], range: NSMakeRange(0, (status as NSString).length))
        
        //倒着替换表情描述,因为正着替换会出现富文本的长度边度,到时范围超出
        for matchResult in matchReulstArray.reversed() {
            
            //匹配表情描述的范围
            let range = matchResult.range
            
            //根据表情的范围获取表情描述
            let chs = (status as NSString).substring(with: range)
            
            //根据表情描述查找表情模型
            if let emoticon = VVEmoticonTools.sharedTools.selectedEmoticon(chs: chs) {
                
                //根据表情模型创建表情富文本
                let emoticonAttributedStr = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: UIFont.systemFont(ofSize: 13))
                //根据表情描述的范围替换表情富文本
                attributedStr.replaceCharacters(in: range, with: emoticonAttributedStr)

            }
            
        }
        //设置整体富文本的字体大小,防止大小不同
        attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 13)], range: NSMakeRange(0, attributedStr.length))
        
        return attributedStr
       
    }
    
    //处理来源数据
    fileprivate func handleSourceContent(source: String) {
        
        //开始截取的范围  结束截取的范围
        if let startRange = source.range(of: "\">"), let endRange = source.range(of: "</") {
            
            //表示在字符传中最大的光标索引
            let startIndex = startRange.upperBound
            
            //表示在字符串中最小的光标索引
            let endIndex = endRange.lowerBound
            
            //完成字符串的截取
            sourceContent = "来自: " + source.substring(with: startIndex..<endIndex)
            
        }
        
    }
    
    //处理转发微博显示内容的逻辑
    fileprivate func handleReweetConten(status: VVStatus) {
        
        //判断是否有转发微博
        if let retweetStatus = status.retweeted_status {
            
            if let screenName = retweetStatus.user?.screen_name, let text = retweetStatus.text {
                
                //多个可选的判断
                retweetContent = "@\(screenName):\(text)"
                
                //设置转发微博富文本
                retweetAttributedString = handleEmoticonAttributedString(status: retweetContent!)
                
            }
            
        }
    }
    
    //处理会员等级图片1-6
    fileprivate func handleMbrankImage(mbrank: Int) {
        
        if mbrank >= 1 && mbrank <= 6 {
            
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        
    }
    
    fileprivate func hanleVerifiedTyeImage(verifiedType: Int) {
        
        switch verifiedType {
        case 1:
            
            verifiedTypeImage = UIImage(named: "avatar_vip")
          
        case 2,3,5:
            
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
            
        case 220:
            
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
            
        default:
            verifiedTypeImage = nil
        }
        
        
    }
    
}
    

